package com.qzsoft.zhjd.laboratory.modules.common;

import java.nio.ByteOrder;
import java.util.Arrays;

/**
 * 字节工具类 （重复且好用轮子）
 *
 * @author MacUncle
 * @see com.qzsoft.zhjd.common.utils.ZhjdIotUtils
 */
public abstract class ByteUtils {

    /**
     * 将 MODBUS CRC16[2B] 值附加在 frame 末尾（修改 frame，返回新数组）
     */
    public static byte[] appendModBusCRC16(byte[] withoutCrc) {
        int crc = calculateCRC16LittleEndian(withoutCrc, 0, withoutCrc.length);
        int crcLo = crc & 0xFF;
        int crcHi = (crc >> 8) & 0xFF;
        byte[] out = Arrays.copyOf(withoutCrc, withoutCrc.length + 2);
        out[out.length - 2] = (byte) crcLo; // Modbus 低字节先发
        out[out.length - 1] = (byte) crcHi;
        return out;
    }

    /**
     * MODBUS CRC16[2B] 校验：输入整个帧（含帧头..数据..CRC），返回 true 如果 CRC 匹配
     * <p>
     *
     * @param frame       原始帧数据
     * @param frameOffset 帧数据偏移量
     * @param frameLen    帧长度
     * @param crcOffset   CRC数据偏移量
     * @return boolean 验证是否通过
     */
    public static boolean checkModBusCRC16(byte[] frame, int frameOffset, int frameLen, int crcOffset) {
        if (frameLen < 3) return false;
        frameLen = frameLen - crcOffset; // 通常是：最后2字节为 CRC

        int calc = calculateCRC16LittleEndian(frame, frameOffset, frameLen);

        // CRC 在帧中为低字节在前还是高字节在前？ 文档未说明 Modbus 默认发送低字节在前
        int crcLo = frame[frameOffset + frameLen] & 0xFF;
        int crcHi = frame[frameOffset + frameLen + 1] & 0xFF;
        int frameCrc = (crcHi << 8) | crcLo; // CRC-16(Modbus) 小端序
        return calc == frameCrc;
    }

    /**
     * CRC-16(Modbus)[2B][Little-Endian]
     * <p>
     * 按位法计算。数据过大时，存在计算压力
     *
     * @param data   数据数组
     * @param offset 计算起始偏移量
     * @param length 计算的长度
     * @return int {@link ByteOrder#LITTLE_ENDIAN 小端序}结果值！
     */
    public static int calculateCRC16LittleEndian(byte[] data, int offset, int length) {
        int crc = 0xFFFF; // 初始化 CRC 为 0xFFFF
        for (int i = offset; i < offset + length; i++) {
            crc ^= (data[i] & 0xFF); // 将当前字节与 CRC 的低字节异或
            for (int j = 0; j < 8; j++) { // 对每一位循环处理
                if ((crc & 0x0001) != 0) { // 检查最低位
                    crc >>= 1; // 右移一位
                    crc ^= 0xA001; // 如果最低位为 1，则与多项式 0xA001 异或
                } else {
                    crc >>= 1; // 如果最低位为 0，直接右移
                }
            }
        }
        // 此处是为了处理下 大小端序 的要求！
        int lo = crc & 0xFF; // 取出低位
        int hi = (crc >> 8) & 0xFF; // 取出高位
        return (hi << 8) | lo; // 小端序 (Little-Endian)
        // return (lo << 8) | hi; // 大端序 (Big-Endian)
    }

    /**
     * CRC-16(MSB-LSB)[2B][Big-Endian]
     * <p>
     * 查表法。占用512字节，但是计算压力小
     *
     * @param data       数据数组
     * @param offset     计算起始偏移量
     * @param length     计算的长度
     * @param byteOrders 字节序配置。
     *                   CRC-16(Modbus) 通常为{@link ByteOrder#LITTLE_ENDIAN}小端序；<pre/>
     *                   CRC-16(MSB-LSB) 通常为{@link ByteOrder#BIG_ENDIAN}大端序。<pre/>
     * @return int {@link ByteOrder#BIG_ENDIAN 大端序}结果值！
     */
    public static int calculateCRC16Endian(byte[] data, int offset, int length, ByteOrder byteOrders) {
        int uchCRCHi = 0xFF;
        int uchCRCLo = 0xFF;
        int uIndex;

        for (int i = offset; i < length + offset; i++) {
            uIndex = (uchCRCHi ^ data[i]) & 0xFF; // 注意Java中byte是只读的，需要&0xFF转无符号
            uchCRCHi = (uchCRCLo ^ CRC_HI[uIndex]) & 0xFF; // 计算高位
            uchCRCLo = CRC_LO[uIndex] & 0xFF; // 计算低位
        }

        if (ByteOrder.BIG_ENDIAN.equals(byteOrders)) {
            return (uchCRCHi << 8 | uchCRCLo); // 大端序 (Big-Endian)
        } else if (ByteOrder.LITTLE_ENDIAN.equals(byteOrders)) {
            return (uchCRCLo << 8 | uchCRCHi); // 小端序 (Little-Endian)
        }

        // 默认走标准的Modbus CRC-16 小端序 (Little-Endian)
        return (uchCRCLo << 8 | uchCRCHi);
    }


    /**
     * 计算标准 Modbus CRC-16
     * <p>
     * （返回 0xFFFF 范围内整数[大端序]）
     *
     * @param data   数据数组对象
     * @param offset 计算起始偏移量
     * @param length 需要计算的数据数组长度
     * @return int   默认返回{@link ByteOrder#BIG_ENDIAN}大端序结果值！
     */
    public static int calculateCRC16(byte[] data, int offset, int length) {
        int uchCRCHi = 0xFF; // 高位计算值[1B]
        int uchCRCLo = 0xFF; // 地位计算值[1B]

        for (int i = offset; i < offset + length; i++) {
            int uIndex = (uchCRCHi ^ (data[i] & 0xFF)) & 0xFF;
            uchCRCHi = (uchCRCLo ^ CRC_HI[uIndex]) & 0xFF;
            uchCRCLo = CRC_LO[uIndex] & 0xFF;
        }
        // 返回一个 16-bit（2B）值
        return (uchCRCHi << 8) | uchCRCLo;
    }

    /**
     * 根据指定端序返回 CRC (标准计算仍然是高位在前)
     */
    public static int crcWithEndian(int crc, ByteOrder byteOrder) {

        int hi = (crc >> 8) & 0xFF;
        int lo = crc & 0xFF;

        if (ByteOrder.BIG_ENDIAN.equals(byteOrder)) {
            // 高位在前
            return (hi << 8) | lo;
        }

        if (ByteOrder.LITTLE_ENDIAN.equals(byteOrder)) {
            // 低位在前（Modbus 默认顺序）
            return (lo << 8) | hi;
        }

        // 默认按 Modbus 小端序
        return (lo << 8) | hi;
    }


    /**
     * 将 16 进制字符串（例如 "EB9000010A0B" 或带空格 "EB 90 00 01 0A 0B"）转换为 byte[] 数组。
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null) return new byte[0];
        hexString = hexString.replaceAll("[^0-9A-Fa-f]", ""); // 去掉非十六进制字符（空格、0x等）
        int len = hexString.length();
        if (len % 2 != 0) {
            hexString = "0" + hexString; // 若奇数长度前补0
            len++;
        }
        byte[] bytes = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16));
        }
        return bytes;
    }

    /**
     * 将 byte[] 转为大写十六进制字符串（以空格分隔）。
     */
    public static String bytesToHexString(byte[] bytes) {
        if (bytes == null || bytes.length == 0) return "";
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X ", b));
        }
        return sb.toString().trim();
    }

    // 常用快捷读取

    /**
     * 大端读取 short (2 字节)
     */
    public static short readShortBE(byte[] data, int offset) {
        return ((Number) readNumber(data, offset, 2, ByteOrder.BIG_ENDIAN, Short.class)).shortValue();
    }

    /**
     * 小端读取 short (2 字节)
     */
    public static short readShortLE(byte[] data, int offset) {
        return readNumber(data, offset, 2, ByteOrder.LITTLE_ENDIAN, Short.class).shortValue();
    }

    /**
     * 大端读取 int (4 字节)
     */
    public static int readIntBE(byte[] data, int offset) {
        return readNumber(data, offset, 4, ByteOrder.BIG_ENDIAN, Integer.class).intValue();
    }

    /**
     * 小端读取 int (4 字节)
     */
    public static int readIntLE(byte[] data, int offset) {
        return readNumber(data, offset, 4, ByteOrder.LITTLE_ENDIAN, Integer.class).intValue();
    }

    /**
     * 大端读取 long (8 字节)
     */
    public static long readLongBE(byte[] data, int off) {
        return (long) readNumber(data, off, 8, ByteOrder.BIG_ENDIAN, Long.class);
    }

    /**
     * 小端读取 long (8 字节)
     */
    public static long readLongLE(byte[] data, int off) {
        return (long) readNumber(data, off, 8, ByteOrder.LITTLE_ENDIAN, Long.class);
    }

    // 常用快捷写入
    public static void writeShortBE(byte[] dest, int offset, short value) {
        writeNumber(dest, offset, value, 2, ByteOrder.BIG_ENDIAN);
    }

    public static void writeShortLE(byte[] dest, int offset, short value) {
        writeNumber(dest, offset, value, 2, ByteOrder.LITTLE_ENDIAN);
    }

    public static void writeIntBE(byte[] dest, int offset, int value) {
        writeNumber(dest, offset, value, 4, ByteOrder.BIG_ENDIAN);
    }

    public static void writeIntLE(byte[] dest, int offset, int value) {
        writeNumber(dest, offset, value, 4, ByteOrder.LITTLE_ENDIAN);
    }

    /**
     * 通用读取方法
     */
    public static Number readNumber(byte[] data, int offset, int length, ByteOrder order, Class<?> type) {
        if (offset + length > data.length) {
            throw new IllegalArgumentException("读取越界");
        }

        long bits = 0;
        if (order == ByteOrder.LITTLE_ENDIAN) {
            for (int i = 0; i < length; i++) {
                bits |= ((long) data[offset + i] & 0xFF) << (8 * i);
            }
        } else {
            for (int i = 0; i < length; i++) {
                bits = (bits << 8) | ((long) data[offset + i] & 0xFF);
            }
        }

        if (type == Byte.class) {
            return (byte) bits;
        } else if (type == Short.class) {
            return (short) bits;
        } else if (type == Integer.class) {
            return (int) bits;
        } else if (type == Long.class) {
            return bits;
        } else if (type == Float.class) {
            return Float.intBitsToFloat((int) bits);
        } else if (type == Double.class) {
            return Double.longBitsToDouble(bits);
        } else {
            throw new IllegalArgumentException("不支持的类型: " + type);
        }
    }

    /**
     * 通用写入方法
     */
    public static void writeNumber(byte[] dest, int offset, Number value, int length, ByteOrder order) {
        long bits;
        if (value instanceof Float) {
            bits = Float.floatToIntBits(value.floatValue());
        } else if (value instanceof Double) {
            bits = Double.doubleToLongBits(value.doubleValue());
        } else {
            bits = value.longValue();
        }

        // 小端
        if (order == ByteOrder.LITTLE_ENDIAN) {
            for (int i = 0; i < length; i++) {
                dest[offset + i] = (byte) ((bits >> (8 * i)) & 0xFF);
            }
        } else
        // 大端
        {
            for (int i = 0; i < length; i++) {
                dest[offset + length - 1 - i] = (byte) ((bits >> (8 * i)) & 0xFF);
            }
        }
    }

    /**
     * CRC 高位表 [size:256]
     */
    private static final int[] CRC_HI = {
        0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
        0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
        0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
        0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
        0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
        0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
        0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
        0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
        0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
        0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
        0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
        0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
        0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
        0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
        0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
        0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
        0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
        0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
        0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
        0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
        0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
        0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
        0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
        0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
        0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
        0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
    };

    /**
     * CRC 低位表 [size:256]
     */
    private static final int[] CRC_LO = {
        0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06,
        0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD,
        0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,
        0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A,
        0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4,
        0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
        0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3,
        0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4,
        0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A,
        0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29,
        0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED,
        0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
        0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60,
        0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67,
        0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F,
        0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68,
        0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E,
        0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
        0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71,
        0x70, 0xB0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92,
        0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,
        0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B,
        0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B,
        0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
        0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42,
        0x43, 0x83, 0x41, 0x81, 0x80, 0x40
    };
}
